﻿/*
 * $Author: ammar $
 * 
 * $Date: 2012-03-09 20:55:05 +0100 (vr, 09 mrt 2012) $
 * $LastChangedBy: ammar $
 * $LastChangedRevision: 88 $
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;

// This class is a helper for the dilation edge detection
// Do not use this class for substraction yet, algorithm to implement: Q(i,j) = P1(i,j) - P2(i,j)
namespace TLD_Vision.filters
{
	public class Substract
	{
		public static Image SubstractImages(Image firstImage, Image secondImage)
		{
			Image newImage = new Image(new Bitmap(firstImage.Width, firstImage.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb));

			if(!firstImage.GetBitmap().Size.Equals(secondImage.GetBitmap().Size))
				throw new Exception("Image sizes should be equal.");

			unsafe
			{
				uint* pFirst = (uint*)firstImage.GetDataPointer();
				uint* pSecond = (uint*)secondImage.GetDataPointer();
				uint* pNew = (uint*)newImage.GetDataPointer();

				uint pixel1, pixel2;

				// Iterate over all pixels, if both pixels are dark then make the new pixel light
				// Else copy the pixel of the first input image
				for(int px = 0; px < firstImage.Width * firstImage.Height; px++)
				{
					pixel1 = pFirst[px] & 0x00FFFFFF;
					pixel2 = pSecond[px] & 0x00FFFFFF;

					if(pixel1 < 0x101010 && pixel2 < 0x101010)
						pNew[px] = 0xFFFFFFFF;
					else
						pNew[px] = pFirst[px];
				}
			}

			firstImage.Unlock();
			secondImage.Unlock();
			newImage.Unlock();

			return newImage;
		}
	}
}
